﻿using LeSoft.Application.Bussiness;
using LeSoft.Application.Cache;
using LeSoft.Application.Code;
using LeSoft.Application.Entity;
using LeSoft.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LeSoft.Application.Web.Areas.BaseManage.Controllers
{
    
    public class AccountController :MvcControllerBase
    {
        private AccountBLL accountBLL = new AccountBLL();
        private OrganizeCache organizeCache = new OrganizeCache();
        private DepartmentCache departmentCache = new DepartmentCache();
        private WorkerBLL workerBLL = new WorkerBLL();
        private CustomerInfoBLL customerInfoBLL = new CustomerInfoBLL();
        private VendorBLL vendorBLL = new VendorBLL();
        private static Byte[] bt;
        #region 视图功能
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult Form()
        {
            ViewBag.Html = GenerateSelect();
            return View();
        }
        /// <summary>
        /// 重置密码
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult RevisePassword()
        {
            return View();
        }
        #endregion

        #region 获取数据
        /// <summary>
        /// 分页获取数据
        /// </summary>
        /// <param name="pagination"></param>
        /// <param name="queryJson"></param>
        /// <returns></returns>
        [HttpGet]
        [HandlerAction(OperationType.GetList, "账户管理")]
        public ActionResult GetPageListJson(Pagination pagination, string queryJson)
        {
            var watch = CommonHelper.TimerStart();
            var data = accountBLL.GetPageList(pagination, queryJson);
            var JsonData = new
            {
                rows = data,
                total = pagination.total,
                page = pagination.page,
                records = pagination.records,
                costtime = CommonHelper.TimerEnd(watch)
            };
            return Content(JsonData.ToJson());
        }

        [HttpGet]
        public ActionResult GetUserTreeJson(string AccountType)
        {
            var treeList = new List<TreeEntity>();      
            if (AccountType == "2")
            {
                var userdata = workerBLL.GetList();               
                var organizedata = organizeCache.GetList().ToList();
                if(OperatorProvider.Provider.Current().UserId !="System") 
                    organizedata=organizedata.Where(t => t.OrganizeId == OperatorProvider.Provider.Current().CompanyId).ToList();
                if (organizedata.Count == 1 && organizedata[0].ParentId != "0") organizedata[0].ParentId = "0";
                var departmentdata = departmentCache.GetList();              
                foreach (OrganizeEntity item in organizedata)
                {
                    #region 机构
                    TreeEntity tree = new TreeEntity();
                    bool hasChildren = organizedata.Count(t => t.ParentId == item.OrganizeId) == 0 ? false : true;
                    if (hasChildren == false)
                    {
                        hasChildren = departmentdata.Count(t => t.OrganizeId == item.OrganizeId) == 0 ? false : true;
                        if (hasChildren == false)
                        {
                            continue;
                        }
                    }
                    tree.id = item.OrganizeId;
                    tree.text = item.FullName;
                    tree.value = item.OrganizeId;
                    tree.parentId = item.ParentId;
                    tree.isexpand = true;
                    tree.complete = true;
                    tree.hasChildren = hasChildren;
                    tree.Attribute = "Sort";
                    tree.AttributeValue = "Organize";
                    treeList.Add(tree);
                    #endregion
                }
                foreach (DepartmentEntity item in departmentdata)
                {
                    #region 部门
                    TreeEntity tree = new TreeEntity();
                    tree.id = item.DepartmentId;
                    tree.text = item.FullName;
                    tree.value = item.DepartmentId;
                    if (item.ParentId == "0")
                    {
                        tree.parentId = item.OrganizeId;
                    }
                    else
                    {
                        tree.parentId = item.ParentId;
                    }
                    tree.isexpand = true;
                    tree.complete = true;
                    tree.hasChildren = true;
                    tree.Attribute = "Sort";
                    tree.AttributeValue = "Department";
                    treeList.Add(tree);
                    #endregion
                }             
                foreach (WorkerEntity item in userdata)
                {
                    #region 员工
                    TreeEntity tree = new TreeEntity();
                    tree.id = item.Id;
                    tree.text = item.Name;
                    tree.value = item.Id;
                    tree.parentId = item.DepartmentId;
                    tree.title = item.Code;
                    tree.isexpand = true;
                    tree.complete = true;
                    tree.hasChildren = false;
                    tree.Attribute = "Sort";
                    tree.AttributeValue = "User";
                    tree.img = "fa fa-user";
                    treeList.Add(tree);
                    #endregion
                }
                return Content(treeList.TreeToJson());
            }
            else if (AccountType == "3")
            {
                var userdata = customerInfoBLL.GetList();
                foreach (CustomerInfoEntity item in userdata)
                {
                    #region 客户
                    TreeEntity tree = new TreeEntity();
                    tree.id = item.Id;
                    tree.text = item.Name;
                    tree.value = item.Id;
                    tree.parentId ="0";
                    tree.title = item.Code;
                    tree.isexpand = true;
                    tree.complete = true;
                    tree.hasChildren = false;
                    tree.Attribute = "Sort";
                    tree.AttributeValue = "User";
                    tree.img = "fa fa-user";
                    treeList.Add(tree);
                    #endregion
                }
                return Content(treeList.TreeToJson());
            }
            else if (AccountType == "4")
            {
                var userdata = vendorBLL.GetList();
                foreach (VendorEntity item in userdata)
                {
                    #region 供应商
                    TreeEntity tree = new TreeEntity();
                    tree.id = item.Id;
                    tree.text = item.FullName;
                    tree.value = item.Id;
                    tree.parentId = "0";
                    tree.title = item.EnCode;
                    tree.isexpand = true;
                    tree.complete = true;
                    tree.hasChildren = false;
                    tree.Attribute = "Sort";
                    tree.AttributeValue = "User";
                    tree.img = "fa fa-user";
                    treeList.Add(tree);
                    #endregion
                }
                return Content(treeList.TreeToJson());
            }
            else
            {
                return null;
            }                 
        
        }

        [HttpGet]
        [HandlerAction(OperationType.GetForm, "账户管理")]
        public ActionResult GetFormJson(string keyValue)
        {
            var data = accountBLL.GetEntity(keyValue);
            if(data.HeadIcon!=null) GenerateImage(data.HeadIcon,data.Id);          
            return Content(data.ToJson());
        }

        [HttpGet]
        public ActionResult ExistAccount(string Account, string keyValue)
        {
            bool IsOk = accountBLL.ExistAccount(Account, keyValue);
            return Content(IsOk.ToString());
        }

        [HttpGet]
        public ActionResult GetAccountType()
        {
            var treeList = new List<TreeEntity>();
            treeList.Add(new TreeEntity { id ="5",text = "其他",value = "其他",parentId = "0"});
            if (SystemInfo.CurrentProductId.Contains("101")) { treeList.Add(new TreeEntity { id = "2", text = "员工", value = "员工", parentId = "0" });  }
            if (SystemInfo.CurrentProductId.Contains("102")) { treeList.Add(new TreeEntity { id = "3", text = "客户", value = "客户", parentId = "0" });  }
            if (SystemInfo.CurrentProductId.Contains("103")) { treeList.Add(new TreeEntity { id = "4", text = "供应商", value = "供应商", parentId = "0" }); }
            return Content(treeList.ToJson());
        }
        #endregion

        #region 提交数据

        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Submit,"账户管理")]
        public ActionResult SaveForm(string keyValue, string strAccountEntity)
        {
            AccountEntity accountEntity = strAccountEntity.ToObject<AccountEntity>();
            accountEntity.CustomerCode = OperatorProvider.Provider.Current().CustomerCode;
            accountEntity.HeadIcon = bt;
            if(!string.IsNullOrEmpty(keyValue)){
                accountEntity.Id =keyValue;
            }
           else if (string.IsNullOrEmpty(accountEntity.Id) && accountEntity.AccountType == 5)
            {
                accountEntity.Id = Guid.NewGuid().ToString();                
            }
            string objectId = accountBLL.SaveForm(keyValue, accountEntity);          
            return Success("操作成功。");
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.Delete, "账户管理")]
        public ActionResult RemoveForm(string keyValue)
        {
            if (keyValue == "System")
            {
               return Error("系统账户不能删除");
            }
            else if (keyValue == OperatorProvider.Provider.Current().UserId)
            {
                return Error("不能删除自己");
            }
            else
            {
                accountBLL.RemoveForm(keyValue);
                return Success("删除成功。");
            }
           
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Submit, "账户管理","重置密码")]
        public ActionResult SaveRevisePassword(string keyValue, string Password)
        {
            //if (keyValue == "System")
            //{
            //    return Error("当前账户不能重置密码");
            //}
            accountBLL.RevisePassword(keyValue, Password);
            return Success("密码修改成功，请牢记新密码。");
        }

        [HttpPost]
        [AjaxOnly]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult DisabledAccount(string keyValue)
        {
            if (keyValue == "System")
            {
                throw new Exception("当前账户不禁用");
            }
            accountBLL.UpdateState(keyValue, 0);
            return Success("账户禁用成功。");
        }
        /// <summary>
        /// 启用账户
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult EnabledAccount(string keyValue)
        {
            accountBLL.UpdateState(keyValue, 1);
            return Success("账户启用成功。");
        }
        #endregion

        /// <summary>
        /// 导出用户
        /// </summary>
        /// <returns></returns>
        public ActionResult ExportUserList()
        {
            accountBLL.GetExportList();
            return Success("导出成功。");
        }

        /// <summary>
        /// 上传头像
        /// </summary>
        /// <returns></returns>
        public ActionResult UploadFile()
        {
            HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
            //没有文件上传，直接返回
            if (files[0].ContentLength == 0 || string.IsNullOrEmpty(files[0].FileName))
            {
                return HttpNotFound();
            }
            var fs = files[0].InputStream;
             bt = new byte[fs.Length];
            fs.Read(bt, 0, Convert.ToInt32(fs.Length));
            fs.Close();
            return Success("上传成功。");
        }
        /// <summary>
        /// 读取头像
        /// </summary>
        /// <param name="bt"></param>
        /// <param name="name"></param>
        public void GenerateImage(Byte[] bt,string name)
        {           
            int ArraySize = bt.GetUpperBound(0);//获得数据库中存储的位流数组的维度上限，用作读取流的上限           
            string virtualPath =HttpRuntime.AppDomainAppPath+ string.Format("/Resource/PhotoFile/{0}.jpg", name);
            //创建文件夹
            string path = Path.GetDirectoryName(virtualPath);
            Directory.CreateDirectory(path);
            FileStream fs = new FileStream(virtualPath, FileMode.OpenOrCreate, FileAccess.Write);
            fs.Write(bt, 0, ArraySize);
            fs.Close();   //-- 写入到virtualPath。
        }

        public string GenerateSelect()
        {
            string _html=string.Empty;
            _html+=" <div class='checkbox user-select'>";
            if (SystemInfo.CurrentProductId.Contains("101")||SystemInfo.CurrentProductId.Contains("102")||SystemInfo.CurrentProductId.Contains("103")) {  
                _html+= "<label><input id='IsBS' type='checkbox' />PC端</label>";
              }
            if (SystemInfo.CurrentProductId.Contains("201")||SystemInfo.CurrentProductId.Contains("202")||SystemInfo.CurrentProductId.Contains("203")) { 
                  _html+=  "<label><input id='IsApp' type='checkbox' />移动端 </label>";
            }
            //if (SystemInfo.CurrentProductId.Contains("301")||SystemInfo.CurrentProductId.Contains("302")||SystemInfo.CurrentProductId.Contains("303")) {
            //    _html += "<label><input id='IsWechat' type='checkbox' />WeChat用户</label>";
            //}
             //_html+="<label><input id='EnabledMark' type='checkbox' checked='checked' />有效 </label>";
             //_html+="<label><input id='CheckOnLine' type='checkbox' />启用单点登陆</label>";
             _html+="  </div>";
             return _html;
        }
    }
}
